<template>
    <van-dialog
      v-model:show="showDialog"
      :show-cancel-button="false"
      :showConfirmButton="false"
      :close-on-click-overlay="true"
      @close="handleClose"
      class="custom-charge-dialog"
    >
      <!-- 自定义头部 -->
      <template #title>
        <div class="dialog-header">
          <span class="dialog-title">预约充电</span>
          <van-icon
            name="cross"
            size="20"
            class="close-icon"
            @click="handleClose"
          />
        </div>
      </template>
  
      <div class="charge-dialog-content">
        <!-- 时间选择区域 -->
        <div class="time-select-container">
          <div class="time-label left-label">车队将于每天</div>
          
          <!-- 中间滑动时间选择器 -->
          <div class="time-picker-wrapper">
            <div 
              class="time-picker"
              @touchstart="handleTouchStart"
              @touchmove="handleTouchMove"
              @touchend="handleTouchEnd"
              :style="{ transform: `translateY(${translateY}px)` }"
            >
              <div 
                v-for="(time, index) in timeOptions" 
                :key="index"
                class="time-option"
                :class="{ active: index === activeIndex + 1 }" 
                :data-index="index"
              >
                {{ time }}
              </div>
            </div>
            <!-- 选择指示器 -->
            <div class="picker-indicator"></div>
          </div>
          
          <div class="time-label right-label">开启充电</div>
        </div>
  
        <!-- 充电目标区域 -->
        <div class="target-section">
          <div class="target-desc">
            <span>充电目标：</span>
            <span class="target-value">{{ selectedTarget }}%</span>
          </div>
          <van-slider
            v-model="targetSliderValue"
            :min="50"
            :max="100"
            :step="5"
            @change="handleTargetSliderChange"
            bar-height="4px"
          />
        </div>
  
        <!-- 确定按钮 -->
        <div class="confirm-btn-wrap">
          <van-button type="primary" @click="handleConfirm">确定</van-button>
        </div>
      </div>
    </van-dialog>
  </template>
  
  <script setup>
  import { ref, computed, watch, onMounted } from 'vue';
  // import { Dialog, Icon, Slider, Button, Toast } from 'vant';
  import { updateSocAndTime } from '@/api/api';
  import { Notify } from 'vant';
  import { showToast } from 'vant'; 

// Vue.use(Notify);
  // 接收是否显示弹框的控制值
  const props = defineProps({
    show: {
      type: Boolean,
      default: false
    }
  });
  
  // 用于通知父组件弹框关闭、确认事件
  const emit = defineEmits(['close', 'confirm']);
  
  const showDialog = ref(props.show);
  // 时间相关：5分钟为间隔，从00:00到23:59
  const timeOptions = ref([]);
  const activeIndex = ref(0);
  const itemHeight = 40; // 每个时间选项的高度
  const visibleCount = 3; // 可见的时间选项数量
  const translateY = ref(0); // 滚动的位移量
  
  // 触摸相关变量
  const touchStartY = ref(0);
  const startTranslateY = ref(0);
  const isDragging = ref(false);
  
  // 充电目标：50 - 100，步长5
  const targetSliderValue = ref(80); // 默认80%
  
  // 监听props.show变化，同步控制弹框显示
  watch(
    () => props.show,
    (newVal) => {
      showDialog.value = newVal;
    }
  );
  
  // 生成时间选项列表（5分钟间隔）
  const generateTimeOptions = () => {
    const options = [];
    for (let i = 0; i <= 1439; i += 5) {
      const hours = Math.floor(i / 60);
      const minutes = i % 60;
      options.push(
        `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`
      );
    }
    return options;
  };
  
  // 计算选中的时间（现在返回第二个时间点）
  const selectedTime = computed(() => {
    const secondIndex = activeIndex.value >= timeOptions.value.length - 1 ? 0 : activeIndex.value + 1;
    return timeOptions.value[secondIndex] || '00:00';
  });
  
  // 充电目标相关
  const selectedTarget = computed(() => targetSliderValue.value);
  const handleTargetSliderChange = (value) => {
    targetSliderValue.value = value;
  };
  
  // 触摸开始
  const handleTouchStart = (e) => {
    isDragging.value = true;
    touchStartY.value = e.touches[0].clientY;
    startTranslateY.value = translateY.value;
  };
  
  // 触摸移动
  const handleTouchMove = (e) => {
    if (!isDragging.value) return;
    
    const currentY = e.touches[0].clientY;
    const diff = currentY - touchStartY.value;
    translateY.value = startTranslateY.value + diff;
    
    // 限制滚动范围
    const maxTranslate = 0;
    const minTranslate = -(timeOptions.value.length - visibleCount) * itemHeight;
    if (translateY.value > maxTranslate) {
      translateY.value = maxTranslate;
    } else if (translateY.value < minTranslate) {
      translateY.value = minTranslate;
    }
  };
  
  // 触摸结束，计算最终位置
  const handleTouchEnd = () => {
    if (!isDragging.value) return;
    isDragging.value = false;
    
    // 计算应该选中的索引
    const calculatedIndex = Math.round(-translateY.value / itemHeight);
    setActiveIndex(calculatedIndex);
  };
  
  // 设置选中的索引
  const setActiveIndex = (index) => {
    // 边界检查
    if (index < 0) index = 0;
    if (index >= timeOptions.value.length) index = timeOptions.value.length - 1;
    
    activeIndex.value = index;
    // 计算对应的位移
    translateY.value = -index * itemHeight;
    
    // 确保在可视范围内
    const maxVisibleIndex = timeOptions.value.length - visibleCount;
    if (activeIndex.value > maxVisibleIndex) {
      translateY.value = -maxVisibleIndex * itemHeight;
    }
  };
  
  // 关闭弹框
const handleClose = () => {
  showDialog.value = false;
  emit('update:show', false); // 新增这行，同步更新父组件的v-model
  emit('close');
};
  
  // 确定按钮事件（现在传递第二个时间点）
  const handleConfirm = async () => {
    if (!selectedTime.value) {
      Toast('请选择充电时间');
      return;
    }
    
    emit('confirm', {
      time: selectedTime.value, // 传递第二个时间点
      target: selectedTarget.value
    });
    console.log('开启充电成功')
    const res = await updateSocAndTime({
      targetSoc : selectedTarget.value,
      startTime: selectedTime.value
    })

    showDialog.value = false;
    emit('update:show', false); 
    showToast({
        message: '预约充电成功',
       type: 'success' // 绿色主题
      });
    // Toast.success('预约设置成功');
  };
  
  // 初始化
  onMounted(() => {
    // 生成时间选项
    timeOptions.value = generateTimeOptions();
    
    // 默认选中当前时间附近的选项
    const now = new Date();
    const currentMinutes = now.getHours() * 60 + now.getMinutes();
    // 找到最接近当前时间的5分钟倍数
    const closestIndex = Math.round(currentMinutes / 5);
    setActiveIndex(closestIndex);
  });
  </script>
  
  <style scoped>
  /* 弹框整体样式 */
  .custom-charge-dialog {
    --van-dialog-width: 90%;
    --van-dialog-border-radius: 12px;
    /* 弹框整体往下移动，可根据需求调整数值 */
    margin-top: 30px; 
  }
  
  /* 头部样式 */
  .dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    padding: 10px;
  }
  
  .dialog-title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
  }
  
  .close-icon {
    cursor: pointer;
    color: #999;
    /* 让关闭按钮（x）往右移一点，可微调数值 */
    margin-right: 10px; 
  }
  
  /* 内容区域样式 */
  .charge-dialog-content {
    padding: 10px 16px 20px;
  }
  
  /* 时间选择区域样式 */
  .time-select-container {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 30px;
    padding: 10px 0;
  }
  
  .time-label {
    font-size: 15px;
    color: #333;
    white-space: nowrap;
  }
  
  .left-label {
    margin-right: 8px;
  }
  
  .right-label {
    margin-left: 8px;
    /* 让"开启充电"与高亮时间垂直对齐 */
    display: flex;
    align-items: center; 
  }
  
  /* 时间选择器样式 */
  .time-picker-wrapper {
    flex: 0 0 80px; /* 限制选择器宽度，方便对齐 */
    height: 120px; /* 3个选项的高度 */
    overflow: hidden;
    position: relative;
    text-align: center;
    margin: 0 4px;
  }
  
  .time-picker {
    transition: transform 0.2s ease-out;
    will-change: transform;
  }
  
  .time-option {
    height: 40px;
    line-height: 40px;
    font-size: 16px;
    color: #999;
    transition: all 0.2s;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .time-option.active {
    color: #1568ED;
    font-size: 18px;
    font-weight: bold;
  }
  
  /* 选择指示器 */
  .picker-indicator {
    position: absolute;
    top: 50%;
    left: 0;
    width: 100%;
    height: 40px;
    transform: translateY(-50%);
    pointer-events: none;
    box-sizing: border-box;
    border-top: 1px solid #eee;
    border-bottom: 1px solid #eee;
  }
  
  /* 充电目标区域样式 */
  .target-section {
    margin-bottom: 25px;
    padding: 10px 0;
  }
  
  .target-desc {
    text-align: left;
    margin-bottom: 10px;
    font-size: 15px;
    color: #333;
  }
  
  .target-value {
    color: #1568ED;
    font-weight: bold;
    margin-left: 5px;
  }
  
  /* 确定按钮样式 */
  .confirm-btn-wrap {
    display: flex;
    justify-content: center;
  }
  
  .van-button--primary {
    width: 100%;
    max-width: 160px; /* 限制按钮宽度，更美观 */
    height: 45px;
    border-radius: 22px;
    font-size: 16px;
    background-color: #1568ED;
  }
  
  /* 适配不同屏幕，保证对齐 */
  @media (max-width: 375px) {
    .time-picker-wrapper {
      flex: 0 0 70px;
    }
  }
  :deep(.van-icon-cross:before){
    margin-right: 20px;
  }
  :deep(.van-dialog__footer){
    display: none !important;
    color: red !important;
    visibility: hidden;
  }
  /* :deep(.van-button__content){
    display: none !important;
    color: red !important;
  } */
  /* .van-button__content */
  </style>